package com.web.exiaodao.remote.service.impl;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.entity.Moments;
import com.web.exiaodao.business.repository.MomentsInteractionRepository;
import com.web.exiaodao.business.repository.MomentsRepository;
import com.web.exiaodao.remote.service.ApiMomentsService;
import com.web.exiaodao.remote.vo.MomentsInteractionVo;
import com.web.exiaodao.remote.vo.MomentsVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.result.XaResult;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: zhangl
 * @times: 2016-11-10 14:29:16
 * 类的说明：前端APIMoments接口实现类
 **/
@Service("ApiMomentsService")
@Transactional(readOnly = false)
public class ApiMomentsServiceImpl extends BaseService<Moments> implements ApiMomentsService {

    private static final Logger LOGGER = Logger.getLogger(ApiMomentsServiceImpl.class);

    @Autowired
    MomentsRepository momentsRepository;

    @Autowired
    MomentsInteractionRepository momentsInteractionRepository;

    @Override
    public XaResult<MomentsVo> findOne(Long tId) throws BusinessException {
        Moments obj = momentsRepository.findByIdAndStatusNot(tId, XaConstant.Status.delete);
        XaResult<MomentsVo> xr = new XaResult<MomentsVo>();
        if (XaUtil.isNotEmpty(obj)) {
            xr.setObject(new MomentsVo(obj));
            xr.getObject().setId(obj.getId());
            LOGGER.info("查询单个实体----->Moments");
        } else {
            xr.error(XaConstant.Message.object_not_find);
            LOGGER.info(XaConstant.Message.object_not_find);
            throw new BusinessException(XaConstant.Message.object_not_find);
        }
        return xr;
    }


    @Override
    public XaResult<MomentsVo> deleteWorkGroup(String modelIds, Integer status, String userId) {
        XaResult<MomentsVo> xr = new XaResult<MomentsVo>();
        if (status == null) {
            status = XaConstant.Status.delete;
        }
        if (modelIds != null) {
            String[] ids = modelIds.split(",");
            for (String id : ids) {
                Moments obj = momentsRepository.findByIdAndStatusNot(Long.parseLong(id), status);
                if (XaUtil.isNotEmpty(obj)) {
                    if (obj.getUserId().longValue() != Long.parseLong(userId)) {
                        xr.error("只能删除自己发的朋友圈！");
                        return xr;
                    }
                    obj.setStatus(status);
                    obj = momentsRepository.save(obj);

                    MomentsVo vo = new MomentsVo();
                    vo.setContent(obj.getContent());
                    vo.setCreateTime(obj.getCreateTime());
                    vo.setId(obj.getId());
                    vo.setUserId(obj.getUserId());
                    vo.setIsLike(null);
                    vo.setLikes(null);
                    vo.setUserPhoto(null);
                    String[] photos = new String[1];
                    photos[0] = obj.getPhotos();
                    vo.setPhotos(photos);
                    xr.setObject(vo);
                    xr.getObject().setId(obj.getId());
                } else {
                    xr.error(XaConstant.Message.object_not_find);
                    LOGGER.info(XaConstant.Message.object_not_find);
                    return xr;
                }
            }
        }
        LOGGER.info("更改数据状态----->Moments");
        return xr;
    }

    @Override
    public XaResult<List<MomentsVo>> findListNEStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        throw new BusinessException(XaConstant.Message.error_method_no_impl);
    }

    @Override
    public XaResult<List<MomentsVo>> findListEQStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        return this.findListEQStatusByFilter(status, filterParams, pageable, 0);
    }

    @Override
    public XaResult<List<MomentsVo>> findListEQStatusByFilter(Integer status,
                                                              Map<String, Object> filterParams,
                                                              Pageable pageable, long userId)//userId用来判断自己是否点赞
            throws BusinessException {
        XaResult<List<MomentsVo>> xr = new XaResult<List<MomentsVo>>();

        StringBuffer csql = new StringBuffer();
        csql.append("select count(*) FROM tb_xa_moments wg LEFT JOIN tb_xa_user u on wg.user_id=u.id where wg.status=1");

        long searchUserId = NumberUtils.toLong(filterParams.get("EQ_userId")+"");

        List<Object[]> count = this.query(csql.toString(), null, null);
        if (XaUtil.isNotEmpty(count) && count.size() > 0) {
            StringBuffer sql = new StringBuffer();
            sql.append("select wg.id,wg.user_id,u.user_name, wg.create_time,wg.content,wg.photos,u.photo, ");
            String likeCountSqlWhere = userId != 0 ? (" AND  r.user_id= " + userId) : " ";
            sql.append("(SELECT count(*) from tb_xa_momentsinteraction r where r.moment_id=wg.id and r.type=1 AND 1 = 1 " + likeCountSqlWhere + " ) isLike, ");//占位符userId
            sql.append("(SELECT GROUP_CONCAT(uu.user_name) from tb_xa_momentsinteraction r LEFT JOIN tb_xa_user uu on r.user_id = uu.id where r.moment_id=wg.id and r.type=1) likeList ");
            if ( searchUserId > 0) {
                sql.append("FROM tb_xa_moments wg LEFT JOIN tb_xa_user u on wg.user_id=u.id where wg.status=1 AND wg.user_id= " + searchUserId + " ");
            } else {
                sql.append("FROM tb_xa_moments wg LEFT JOIN tb_xa_user u on wg.user_id=u.id where wg.status=1 ");
            }
            sql.append(" order by wg.create_time desc ");
            List<MomentsVo> vos = new ArrayList<>();
            List<Object[]> objs = this.query(sql.toString(), pageable.getPageNumber() * pageable.getPageSize(), pageable.getPageSize());
            for (Object[] obj : objs) {
                MomentsVo vo = new MomentsVo();
                vo.setId(((BigInteger) obj[0]).longValue());
                vo.setUserId(((BigInteger) obj[1]).longValue());
                vo.setUserName((String) obj[2]);
                vo.setCreateTime((String) obj[3]);
                vo.setContent((String) obj[4]);
                vo.setPhotos(XaUtil.isEmpty(obj[5]) ? new String[0] : ((String) obj[5]).split(","));
                vo.setUserPhoto(XaUtil.isEmpty(obj[6]) ? "" : (String) obj[6]);
                if (userId <= 0) {
                    vo.setIsLike(0);
                } else {
                    vo.setIsLike(((BigInteger) obj[7]).intValue() > 0 ? 1 : 0);//userId对应的人是否点赞
                }
                vo.setLikes(XaUtil.isEmpty(obj[8]) ? new String[0] : ((String) obj[8]).split(","));
                //查询该说说的评论列表

                String interactionsSQL = "SELECT mom.id, mom.create_time, mom.content, mom.moment_id, mom.user_id, mom.user_name , mom.type, mom.reply_to_user_id, usr.user_name as reply_to_user_name \n" +
                        "FROM (SELECT  mm.*, uu.user_name FROM tb_xa_momentsinteraction mm LEFT JOIN tb_xa_user uu ON mm.user_id = uu.id WHERE mm.moment_id = ? && mm.type = ? && mm.status <> ?) mom \n" +
                        "LEFT JOIN tb_xa_user usr  \n" +
                        "ON mom.reply_to_user_id = usr.id;";
                List<Object> params = new ArrayList();
                params.add(vo.getId());
                params.add(2);
                params.add(XaConstant.Status.delete);
                List<Object[]> interactionsArr = this.queryParams(interactionsSQL, null, null, params);
                List<MomentsInteractionVo> interactions = new ArrayList<>();
                for (Object[] mVo : interactionsArr) {
                    MomentsInteractionVo mv = new MomentsInteractionVo();
                    mv.setId(((BigInteger) mVo[0]).longValue());
                    mv.setCreateTime(mVo[1] == null ? "" : (String) mVo[1]);
                    mv.setContent((String) mVo[2]);
                    mv.setMomentId((String) mVo[3]);
                    mv.setUserId(((BigInteger) mVo[4]).longValue());
                    mv.setUserName(mVo[5] == null ? "" : (String) mVo[5]);
                    mv.setType(((Integer) mVo[6]));
                    mv.setReplyToUserId(mVo[7] == null ? -1 : ((BigInteger) mVo[7]).longValue());
                    mv.setReplyToUserName(mVo[8] == null ? "" : (String) mVo[8]);
                    interactions.add(mv);
                }
                vo.setInterations(JSON.parseArray(JSON.toJSONString(interactions), MomentsInteractionVo.class));
                vos.add(vo);
            }
            xr.setObject(vos);
        }
        LOGGER.info("分页查询实体集合----->朋友圈");
        return xr;
    }

    @Override
    public XaResult<MomentsVo> multiOperate(String modelIds,
                                            Integer status) throws BusinessException {
        throw new BusinessException(XaConstant.Message.error_method_no_impl);
    }

    @Override
    public XaResult<MomentsVo> createModel(Moments model)
            throws BusinessException {
        XaResult<MomentsVo> xr = new XaResult<MomentsVo>();
        Moments obj = momentsRepository.save(model);
        xr.setObject(new MomentsVo(obj));
        xr.getObject().setId(obj.getId());
        LOGGER.info("新增数据成功----->Moments");
        return xr;
    }

    @Override
    public XaResult<MomentsVo> updateModel(Moments model)
            throws BusinessException {
        throw new BusinessException(XaConstant.Message.error_method_no_impl);
    }

}
